package com.sanji.springmvc;

import com.sanji.springmvc.interceptor.DemoInterceptor;
import com.sanji.springmvc.messageconverter.MyMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import java.util.List;

/**
 * 配置jsp页面解析器ViewResolver,用来映射路径和实际的页面位置
 * 其中，@EnableWebMvc注解会开启一些默认配置,如一些ViewResource或者MessageConverter
 * Created by joe on 17-4-22.
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.sanji.springmvc")
public class MyMvcConfig extends WebMvcConfigurerAdapter {

  @Bean
  public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/classes/views/");
    viewResolver.setSuffix(".jsp");
    viewResolver.setViewClass(JstlView.class);
    return viewResolver;
  }

  /**
   * 重写这个方法，修改访问静态资源的路径
   *
   * @param registry
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {

    //addResourceLocations 指的是文件放置的目录，addResourceHandler对外暴露的访问路径
    registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
  }

  @Bean
  public DemoInterceptor demoInterceptor() {

    return new DemoInterceptor();
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(demoInterceptor());
  }


  /**
   * 跳转到页面（对应的是HelloController中的index访问）
   *
   * @param registry
   */
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/index").setViewName("index");
    registry.addViewController("/converter").setViewName("converter");
    registry.addViewController("/see").setViewName("sse");
  }

  /*@Override
  public void configurePathMatch(PathMatchConfigurer configurer){
    configurer.setUseSuffixPatternMatch(true);
  }*/

  @Bean
  public MyMessageConverter converter() {
    return new MyMessageConverter();
  }

  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(converter());
  }


}
